<template>
  <div class="machineProductionStatistics">
    <DFPageList ref="dfPageListRef" :page-options="pageOptions">
      <template #chart>
        <div class="page-chart machineProductionStatistics__chart">
          <div class="page-chart__head">
            <div class="head-left">
              {{ $t('route.machineProductionStatistics') }}
            </div>
          </div>
          <div class="page-chart__body">
            <v-chart ref="elChart" class="vue-chart" autoresize :option="chartOption" />
          </div>
        </div>
      </template>
    </DFPageList>
  </div>
</template>

<script lang="ts" setup name="MachineProductionStatistics">
  import { useMixins } from '@/hooks/useMixins';
  import lang from './lang';
  import { listMachine } from '@/api/base/machine';
  import { getDateStr, disablePreviousDate2 } from '@/utils/dateUtil';
  import { use } from 'echarts/core';
  import { CanvasRenderer } from 'echarts/renderers';
  import { LineChart } from 'echarts/charts';
  import { chartOptionFn } from './chartOption';
  import VChart from 'vue-echarts';
  import {
    DatasetComponent,
    DataZoomComponent,
    GridComponent,
    LegendComponent,
    TitleComponent,
    ToolboxComponent,
    TooltipComponent,
  } from 'echarts/components';
import { listMachineProductionStatistics } from '@render/api/reportForm/machineProductionStatistics';

  use([
    CanvasRenderer,
    DatasetComponent,
    DataZoomComponent,
    GridComponent,
    LegendComponent,
    TitleComponent,
    ToolboxComponent,
    TooltipComponent,
    LineChart,
  ]);

  const { loadLangFn } = useMixins();

  loadLangFn(lang);

  const chartData = ref({
    legendData: [],
    xAxisData: [],
    seriesData: [],
  });

  const chartOption = computed(() => {
    const option: any = chartOptionFn();
    const { legendData, xAxisData, seriesData } = chartData.value;
    option.legend.data = legendData;
    option.xAxis.data = xAxisData;
    option.series = seriesData;

    if (seriesData.length) {
      option.yAxis.max = undefined;
    } else {
      option.yAxis.max = 1000;
    }
    return option;
  });

  const dfPageListRef: any = ref(null);

  const machineList = ref([]);

  const date = ref({
    createEndTime: `${getDateStr(0)}`,
    createStartTime: `${getDateStr(-9)}`,
    defaultValue: [
      new Date(`${getDateStr(-9)}`).getTime(),
      new Date(`${getDateStr(0)}`).getTime(),
    ],
  });

  const setRequestDataFn = (e) => {
    const { entity } = e;
    entity.dateStartTime = date.value.createStartTime;
    entity.dateEndTime = date.value.createEndTime;
    delete entity.date;

    return {
      ...e,
      entity,
    };
  };

  const beforeResetFn = () => {
    date.value.createStartTime = `${getDateStr(-9)}`;
    date.value.createEndTime = `${getDateStr(0)}`;
  };

  const pageOptions = {
    searchForm: {
      formSchemas: [
        {
          label: 'machineName',
          prop: 'machineCodeList',
          component: 'NSelect',
          options: machineList,
          componentProps: {
            multiple: true,
          },
        },
        {
          label: 'date',
          common: true,
          component: 'NDatePicker',
          defaultValue: date.value.defaultValue,
          componentProps: {
            clearable: false,
            type: 'daterange',
            valueFormat: 'yyyy-MM-dd',
            format: 'yyyy-MM-dd',
            defaultTime: ['00:00:00', '23:59:59'],
            isDateDisabled: disablePreviousDate2,
            onUpdateValue: (_, v: string[]) => {
              if (v) {
                date.value.createStartTime = v[0];
                date.value.createEndTime = v[1];
              } else {
                date.value.createStartTime = '';
                date.value.createEndTime = '';
              }
            },
          },
        },
      ],
      beforeResetFn,
      requestFn: async(data) => {
        const newData = setRequestDataFn(data);

        const res = await listMachineProductionStatistics(newData);

        chartData.value = parseChartData(res.data || [])
        // console.log(newData);
      },
    },
    table: {
      noTable: true,
      afterSlotName: 'chart',
    },
  };

  const initDictData = async () => {
    const res = await Promise.all([listMachine()]);

    const [res2] = res;

    machineList.value =
      res2?.data.map((item) => ({ label: item.machineName, value: item.machineCode })) || [];

    nextTick(() => {
      dfPageListRef.value?.reloadTableFn();
    });
  };

  initDictData();

  // const data = [
  //   {
  //     date: '2023-10-01',
  //     data:[
  //       {
  //         machineName: '机器1',
  //         outputNum: 100,
  //       },
  //       {
  //         machineName: '机器2',
  //         outputNum: 200,
  //       }
  //     ]
  //   }
  // ]

  function parseChartData(rows) {
    const row = rows[0]?.data || [];
    const xAxisData = rows.map((row) => row.date) || [];
    const legendData = row.map((row) => row.machineName) || [];
    const seriesData =
      row.map((row, i) => {
        const data = rows.map(({ data }) => {
          return data[i].outputNum;
        });
        return {
          name: row.machineName,
          type: 'line',
          data,
        };
      }) || [];

    return {
      legendData,
      xAxisData,
      seriesData,
    };
  }
</script>

<style lang="less" scoped>
  .machineProductionStatistics {
    padding: 0;
    height: 100%;
    &__chart {
      width: 100%;
      min-height: calc(100% - 120px);
    }
  }
  .page-chart {
    margin-top: 16px;
    border-radius: 2px;
    // padding: 24px;
    background: #fff;
    &__head {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 44px;
      .head-left {
        font-size: 16px;
        font-weight: 500;
        color: #222;
      }
    }
  }
  .vue-chart {
    width: 100%;
    height: 460px;
  }
</style>
